package cn.sinata.xldutils_kotlin.utils

import android.text.TextUtils
import android.util.Base64
import java.io.File
import java.net.URLDecoder
import java.net.URLEncoder
import java.nio.charset.Charset
import java.util.regex.Pattern


/**
 * 字符串长度。中文算2个字符。英文算1个字符计算。
 */
fun String?.lengthCN():Int{

    if (this.isNullOrEmpty()) {
        return 0
    }
    var len = 0
    var count = 0
    while (count < this!!.length) {
        val c = get(count)
        if (c.toInt() < 128) {
            len += 1
        } else {
            len +=2
        }
        count++
    }
    return len
}

/**
 * 是否null或者'null'字符
 */
fun String?.isNulls():Boolean=isNullOrEmpty()||equals("null")

/**
 * urlEncode
 */
fun String?.urlEncode():String{
    return if (isNullOrEmpty()) "" else URLEncoder.encode(this, "utf-8")
}

/**
 * urlDecode
 */
fun String?.urlDecode():String{
    return if (isNullOrEmpty()) "" else URLDecoder.decode(this, "utf-8")
}

/**
 * base64
 */
fun String?.base64(charset: Charset = Charsets.UTF_8):String{
    return if (isNullOrEmpty()) "" else Base64.encodeToString(this!!.toByteArray(charset),Base64.DEFAULT)
}

/**
 * 是否有效手机号
 */
fun String?.isValidPhone():Boolean{
    if (isNullOrEmpty()) {
        return false
    }
    if (this!!.length != 11) {
        return false
    }
    val expression = "(^(13|14|15|17|18)[0-9]{9}$)"
    val pattern = Pattern.compile(expression)
    val matcher = pattern.matcher(this)
    if (matcher.matches()) {
        return true
    }
    return false
}

/**
 * 是否有效邮箱地址
 */
fun String?.isValidEmail():Boolean{
    if (isNullOrEmpty()){
        return false
    }
    val pattern = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$")
    val matcher = pattern.matcher(this)
    if (matcher.matches()) {
        return true
    }
    return false
}

/**
 * 返回隐藏后的手机号，
 */
fun String?.hidePhone():String{
    if (isNullOrEmpty()) {
        return ""
    }
    if (this!!.length < 7) {
        return this
    }
    return substring(0,3)+"****"+substring(length-4,length)
}

/**
 * 隐藏身份证号，必须不为null并且length大于10才返回处理后的字符串
 */
fun String?.hideIdCard():String{
    if (isNullOrEmpty()) {
        return ""
    }
    if (this!!.length < 10) {
        return this
    }
    return substring(0,6)+"********"+substring(length-4,length)
}

fun String?.isFilePath() : Boolean{
    if (isNullOrEmpty()) {
        return false
    }
    return File(this).exists()
}